<?php
namespace Menory\SMS\Adapter\HuaXin;

use Exception;
use Menory\SMS\SMSError;
use Menory\SMS\SMSMessage;
use Menory\Standard\Sms\AbstractSMSCenter;

class SMSCenter extends AbstractSMSCenter {

    /**
     * 发送短信
     * @param string $messageType
     * @param string $phone
     * @return array
     */
    public function sendMessage($messageType, $phone) {

        $messageTplId = null;
        /** @var SMSMessage $message */
        foreach ($this->messagePool as $message) {
            if ($message->getMessageType() == $messageType) { $messageTplId = $message->getMessageTplId(); }
        }
        if ($messageTplId === null) { return [null, new SMSError("不存在的短信模板：{$messageType}")]; }

        $code    = $this->genCode(6);
        $request = [
            "templateId"  => $messageTplId,
            "sign_method" => "md5",
            "dynadatas"   => urlencode("{\"minute\":\"2\",\"code\":\"{$code}\",\"destination\":\"{$phone}\"}"),
            "signingId"   => "1470812764629582",
            "productId"   => "B2016000413",
            "appid"       => "APP0d9e000112",
            "timestamp"   => date("Y-m-d H:i:s")
        ];
        $request["sign"] = $this->auth->genSign($request);

        $response = self::curlASJson("http://apisms.huaxincloud.com:8081/custom/CI2016000367/Sms/putDynaSms/", $request);

        if ($response->errorCode == 0) {
            $this->cache($messageType, $phone, $code);
            return [$code, null];
        }

        return [$code, new SMSError($response->msg, SMSError::API_FAIL)];

    }

    /**
     * @param $url
     * @param null $postFields
     * @return mixed
     * @throws Exception
     */
    private static function curlASJson($url, $postFields = null) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, "huaxin-php");
        // https 请求
        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        $jsonPostFields = json_encode($postFields);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Accept: application/json',
            'Content-Type: application/json;charset=utf-8',
            'Content-Length: ' . strlen($jsonPostFields),
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPostFields);
        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            throw new Exception(curl_error($ch), 0);
        } else {
            $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 !== $httpStatusCode) {
                throw new Exception($response, $httpStatusCode);
            }
        }
        curl_close($ch);
        return json_decode($response);

    }

}